<?php
/**
 * （Logic）解析退货报告
 *
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Amazon\AmazonOrder;
use App\Models\Amazon\FbaCustomerReturn;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductAmazonSku;
use App\Util\RExcel;
class ParseCustomerReturnReport
{
    /**
     * 解析CustomerReturn
     * @param $file
     * @param $account
     * @return int
     */
    public static function exeParse($file,$account){
        $lines = RExcel::importFile($file);
        $i = 0;
        $count = 0;
        $head = [];
        try{
            foreach($lines as $_str){
                $str = ParseReport::getReplaceStr($_str);
                if($i == 0){
                    $head = ParseReport::getTableHeadKey($str,self::$_keys);
                    if(empty($head))return 2;
                }else{
                    $flag = self::_addCustomerReturn($account->id,$head,$str);
                    $flag && $count++;
                }
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i==($count+1) ? 2 : 3;
    }

    private static $_keys = ['return-date','order-id', 'sku','asin',  'fnsku', 'quantity', 'detailed-disposition','fulfillment-center-id','reason','customer-comments'];

    /**
     * 添加CustomerReturn
     * @param $accountId
     * @param $head
     * @param $str
     * @return bool
     */
    private static function _addCustomerReturn($accountId,$head,$str){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keys;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        if(!$temp[$head['sku']])return true;
        $returnDate = gmdate('Y-m-d H:i:s',strtotime($temp[$head['return-date']]));
        $count = FbaCustomerReturn::query()
            ->where('account_id',$accountId)
            ->where('return_date',$returnDate)
            ->where('order_id',$temp[$head['order-id']])
            ->where('sku',$temp[$head['sku']])
            ->where('quantity',$temp[$head['quantity']])
            ->where('fulfillment_center_id',$temp[$head['fulfillment-center-id']])
            ->count();
        if($count > 0)return true;
        $order = AmazonOrder::query()->where('amazon_order_id',$temp[$head['order-id']])->first();
        $countryId = AmazonCountry::getCountryIdByMarketplaceId($order->marketplace_id ?? 0);
        $pSkuId = ProductAmazonSku::query()->where('seller_sku',$temp[$head['sku']])->value('psku_id');
        $re = FbaCustomerReturn::query()->create([
            'account_id' => $accountId,
            'country_id' => $countryId ?: 0,
            'psku_id' => $pSkuId ?: 0,
            'return_date' => $returnDate,
            'purchase_date' => $order->purchase_date ?? null,
            'order_id' => $temp[$head['order-id']],
            'sku' => $temp[$head['sku']],
            'asin' => $temp[$head['asin']],
            'fnsku' => $temp[$head['fnsku']],
            'quantity' => $temp[$head['quantity']],
            'detailed_disposition' => $temp[$head['detailed-disposition']],
            'fulfillment_center_id' => $temp[$head['fulfillment-center-id']],
            'reason' => $temp[$head['reason']] ?: null,
            'customer_comments' => $temp[$head['customer-comments']] ?: null,
            'status' => !$temp[$head['customer-comments']] ? 2 : 0,
        ]);
        return !$re ? false : true;
    }
}
